import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';
import 'package:toys_flutter/pages/UserDetail.dart';
import 'package:toys_flutter/utils/index.dart';

class MyFenSi extends StatefulWidget {
  const MyFenSi({super.key});

  @override
  State<MyFenSi> createState() => _MyFenSiState();
}

class _MyFenSiState extends State<MyFenSi> {
  List<dynamic> _followedList = [];
  int page = 1;
  bool isMore = true;

  @override
  void initState() {
    super.initState();
    getData();
  }

  void getData() async {
    var res = await Api.toysFans({'page': page});
    if (res['code'] == 1) {
      // 更新数据
      setState(() {
        _followedList = res['data']['list'] ?? [];
        isMore = res['data']['more'] == 0 ? false : true;
      });
    }
  }

  Future<void> onLoadMore() async {
    if (isMore == false) return;
    page++;
    var res = await Api.toysFans({'page': page});
    if (res['code'] == 1) {
      List<dynamic> newItems = res['data']['list'] ?? [];

      setState(() {
        _followedList = [..._followedList, ...newItems];
        isMore = res['data']['more'] == 0 ? false : true;
      });
    }
  }

  // 模拟数据刷新
  Future<void> _refreshData() async {
    try {
      getData();
    } catch (e) {
      TDToast.showIconText('失败',
          icon: TDIcons.error,
          direction: IconTextDirection.vertical,
          context: context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的粉丝'),
      ),
      body: RefreshableListView(
        onRefresh: _refreshData, // 绑定刷新逻辑
        enableLoadMore: true, // 禁用上拉加载
        onLoadMore: onLoadMore, // 绑定加载更多逻辑
        children: [
          ..._followedList.map((user) {
            return Column(
              children: [
                ListTile(
                  leading: InkWell(
                    onTap: () {
                      // 跳转到用户主页
                      Get.to(UserDetail(userId: user['flow_user']['id']));
                    },
                    child: TDAvatar(
                      size: TDAvatarSize.medium,
                      type: TDAvatarType.normal,
                      avatarUrl: user!['flow_user']['avatar'],
                      // 使用 userData 中的 avatar
                      defaultUrl: 'images/avatar.png', // 使用 userData 中的 avatar
                    ),
                  ),
                  title: Text(user['flow_user']['nickname'] ?? '未知用户'),
                  trailing: Text(
                    DateTimeUtils.convertTimestampToDateString(
                            user['create_time']) ??
                        '未知时间',
                    style: const TextStyle(color: Colors.black38),
                  ),
                ),
                const SizedBox(height: 25),
              ],
            );
          }),
          TDDivider(
            text: isMore ? '上拉加载更多' : '没有更多了',
            alignment: TextAlignment.center,
          ),
          const SizedBox(height: 25),
        ],
      ),
    );
  }
}
